import React, { useState, useRef } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  Box,
  Avatar,
  IconButton,
  Stack,
  styled,
} from '@mui/material';
import EditIcon from '@mui/icons-material/Edit';

interface User {
  id: string;
  username: string;
  name: string;
  email: string;
  avatar: string;
  level: number;
  exp: number;
  nextLevelExp: number;
  joinDate: string;
  bio: string;
}

interface EditProfileDialogProps {
  open: boolean;
  user: User;
  onClose: () => void;
  onSave: (updatedUser: User) => void;
}

const VisuallyHiddenInput = styled('input')({
  clip: 'rect(0 0 0 0)',
  clipPath: 'inset(50%)',
  height: 1,
  overflow: 'hidden',
  position: 'absolute',
  bottom: 0,
  left: 0,
  whiteSpace: 'nowrap',
  width: 1,
});

const EditProfileDialog: React.FC<EditProfileDialogProps> = ({
  open,
  user,
  onClose,
  onSave,
}) => {
  const [formData, setFormData] = useState({
    username: user.username,
    bio: user.bio,
    avatar: user.avatar,
  });
  const [previewAvatar, setPreviewAvatar] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleAvatarClick = () => {
    fileInputRef.current?.click();
  };

  const handleAvatarChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      // 创建本地预览URL
      const reader = new FileReader();
      reader.onloadend = () => {
        setPreviewAvatar(reader.result as string);
      };
      reader.readAsDataURL(file);

      // TODO: 实现头像上传到服务器的功能
      // 这里应该调用API上传图片，获取URL后更新avatar状态
      console.log('Upload avatar:', file);
    }
  };

  const handleSave = () => {
    onSave({
      id: user.id,
      username: formData.username,
      name: user.name,
      email: user.email,
      avatar: previewAvatar || formData.avatar,
      level: user.level,
      exp: user.exp,
      nextLevelExp: user.nextLevelExp,
      joinDate: user.joinDate,
      bio: formData.bio,
    });
    onClose();
  };

  const handleCancel = () => {
    setFormData({
      username: user.username,
      bio: user.bio,
      avatar: user.avatar,
    });
    setPreviewAvatar(null);
    onClose();
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value,
    }));
  };

  return (
    <Dialog open={open} onClose={handleCancel} maxWidth="sm" fullWidth>
      <DialogTitle>编辑个人资料</DialogTitle>
      <DialogContent>
        <Box sx={{ mt: 2 }}>
          <Stack alignItems="center" spacing={2} sx={{ mb: 3 }}>
            <Box sx={{ position: 'relative' }}>
              <Avatar
                src={previewAvatar || formData.avatar}
                sx={{ width: 120, height: 120, cursor: 'pointer' }}
                onClick={handleAvatarClick}
              />
              <IconButton
                sx={{
                  position: 'absolute',
                  bottom: 0,
                  right: 0,
                  backgroundColor: 'background.paper',
                  '&:hover': { backgroundColor: 'action.hover' },
                }}
                onClick={handleAvatarClick}
              >
                <EditIcon />
              </IconButton>
            </Box>
            <VisuallyHiddenInput
              ref={fileInputRef}
              type="file"
              accept="image/*"
              onChange={handleAvatarChange}
            />
          </Stack>

          <TextField
            autoFocus
            margin="dense"
            label="用户名"
            type="text"
            fullWidth
            value={formData.username}
            onChange={handleChange}
            name="username"
            sx={{ mb: 2 }}
          />

          <TextField
            margin="dense"
            label="个性签名"
            multiline
            rows={4}
            fullWidth
            value={formData.bio}
            onChange={handleChange}
            name="bio"
          />
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={handleCancel}>取消</Button>
        <Button onClick={handleSave} variant="contained">
          保存
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default EditProfileDialog;
